package com.seventh.associationsystem.controller;

import com.alibaba.fastjson.JSON;
import com.seventh.associationsystem.bean.HttpResult;
import com.seventh.associationsystem.bean.ResultCode;
import com.seventh.associationsystem.bean.Role;
import com.seventh.associationsystem.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import com.seventh.associationsystem.bean.User;
import com.seventh.associationsystem.service.UserService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@RestController
@RequestMapping("user")
public class UserController {

	@Autowired
    private UserService userService;

	@Autowired
    private RoleService roleService;
	
	@GetMapping("getCurrentUser")
	public User getCurrentUser(){
		User dbUser = ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		return dbUser;
	}
	
	@PostMapping("update")
	public void update(String realName, String grade, String institute, int gender, String cardId, String photoUrl){
		User dbUser = ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		dbUser.setRealName(realName);
		dbUser.setGrade(grade);
		dbUser.setInstitute(institute);
		dbUser.setGender(gender);
		dbUser.setCardId(cardId);
		dbUser.setPhotoUrl(photoUrl);
		userService.update(dbUser);
	}
	
	@PostMapping("resetPassword")
	public void resetPassward(String password){
		User dbUser = ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		dbUser.setPassword(new BCryptPasswordEncoder().encode(password));
		userService.update(dbUser);
	}
	
	@PostMapping("isPasswordRight")
	public String isPasswordRight(String password){
		User dbUser = ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		if(new BCryptPasswordEncoder().matches(password, dbUser.getPassword())){
			return "Y";
		}else{
			return "N";
		}
	}
	
	//FIXME pagination
	@GetMapping("getAllSchoolManager")
    public List<User> getAllSchoolManager() {
	    List<User> users = userService.getAllUsers();
	    List<User> schoolManagers = new ArrayList<>();
	    for (User user : users) {
            Collection<? extends GrantedAuthority> grantedAuthorities = user.getAuthorities();
            for (GrantedAuthority authority : grantedAuthorities) {
                if (authority.getAuthority().compareTo("ROLE_SCHOOL_MANAGER") == 0) {
                    schoolManagers.add(user);
                    break;
                }
            }
        }
        return schoolManagers;
    }

    //FIXME pagination
    @GetMapping("getAllStudent")
    public List<User> getAllStudent() {
        List<User> users = userService.getAllUsers();
        List<User> students = new ArrayList<>();
        for (User user : users) {
            Collection<? extends GrantedAuthority> grantedAuthorities = user.getAuthorities();
            for (GrantedAuthority authority : grantedAuthorities) {
                if (authority.getAuthority().compareTo("ROLE_STUDENT") == 0) {
                    students.add(user);
                    break;
                }
            }
        }
        return students;
    }

    @DeleteMapping("delete")
    public void delete(String uid) {
	    userService.deleteByUid(uid);
    }

    @PostMapping("addSchoolManager")
    public HttpResult addSchoolManager(String username, String password, String retypePassword, String realName) {
        System.out.println(username);
        //TODO limit and verify
        User user = userService.getUserByUsername(username);
        if (user != null) {
            return new HttpResult(ResultCode.USERNAME_EXIST_ERROR, "用户名已存在！");
        }
        if (password.compareTo(retypePassword) != 0) {
            return new HttpResult(ResultCode.PASSWORD_ERROR, "两次输入的密码不一致！");
        }
        User registerUser = new User();
        registerUser.setUsername(username);
        registerUser.setPassword(new BCryptPasswordEncoder().encode(password));
        registerUser.setRealName(realName);
        Role role = roleService.getRoleById(Role.ROLE_SCHOOL_MANAGER);
        registerUser.addRole(role);
        userService.addUser(registerUser);
        return new HttpResult(ResultCode.NO_ERROR);
    }
}
